package com.igoal.dao;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.igoal.entity.DataStatus;
import com.igoal.entity.User;
import com.igoal.entity.UserStatus;

@Repository("userStatusDAO")
public class UserStatusDAOImpl extends GenericDaoHibernate<UserStatus, Long>
		implements UserStatusDAO {

	public UserStatusDAOImpl() {
		super(UserStatus.class);
	}

	public UserStatus saveStatus(UserStatus status) {
		getHibernateTemplate().saveOrUpdate(status);
		getHibernateTemplate().flush();
		return status;
	}

	@Override
	public UserStatus save(UserStatus status) {
		return this.saveStatus(status);
	}
	
	public UserStatus getLastestStatus(User user){
		return getLastestStatus(user.getId());
	}
	
	public UserStatus getLastestStatus(Long userId){
		DetachedCriteria dc = DetachedCriteria.forClass(UserStatus.class);
		dc.add(Restrictions.eq("user.id", userId));
		dc.addOrder(Order.desc("updateDate"));
		getByStatus(dc, DataStatus.USING);
		
		List<UserStatus> result = findByCriteria(dc, 0, 1);
		
		if(result.size() > 0)
			return result.get(0);
		
		return null;
	}
}
